﻿package com.dodock.android.banglapapers;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.webkit.URLUtil;

public class WebServerOperation {

	public static String sendHTTPPostRequestToServer(String urlPath,
			List<NameValuePair> postData, boolean readfromServer)
			throws Exception {
		String data = "";

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(urlPath);

		HttpResponse response = null;
		HttpEntity entity = null;
		InputStream is = null;
		BufferedReader reader = null;

		httppost.setEntity(new UrlEncodedFormEntity(postData, "UTF-8"));
		if (BanglaNews.COOKIESTORE == null)
			BanglaNews.COOKIESTORE = ((DefaultHttpClient) httpclient)
					.getCookieStore();
		else
			((DefaultHttpClient) httpclient)
					.setCookieStore(BanglaNews.COOKIESTORE);

		response = httpclient.execute(httppost);

		if (readfromServer) {

			entity = response.getEntity();

			is = entity.getContent();

			reader = new BufferedReader(
					new InputStreamReader(is, "iso-8859-1"), 8);

			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null) {

				sb.append(line);

			}

			is.close();
			data = sb.toString();
		}

		return data.trim();
	}

	public static String downLoadFile(String fileUrl, String savePath)
			throws Exception {
		RandomAccessFile file = null;
		if (!URLUtil.isNetworkUrl(fileUrl)) {
			return "Not Network URL";
		}

		InputStream is = null;
		URL url = null;
		try {
			url = new URL(fileUrl);
		} catch (MalformedURLException e) {
			return "URL format is not correct";
		}
		URLConnection urlConnection = null;
		try {
			urlConnection = url.openConnection();
			// urlConnection.setConnectTimeout(60000);
			// urlConnection.setReadTimeout(60000);
			urlConnection.connect();
		} catch (Exception e) {
			return "Connection Timeout";
		}

		int contentLength = urlConnection.getContentLength();
		if (contentLength < 1)
			return "Invalid Content";

		File fl = new File(savePath);
		if (!fl.exists())
			fl.mkdirs();

		try {
			file = new RandomAccessFile(savePath + getFileName(url), "rw");
		} catch (FileNotFoundException e) {
			return "Couldn't create file to local directory";
		}
		try {
			file.seek(0);
			is = urlConnection.getInputStream();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		byte buf[] = new byte[128];

		do {
			int numread = 0;
			try {
				numread = is.read(buf);
			} catch (Exception e) {
				return "Read timeout";
			}
			if (numread <= 0)
				break;
			try {
				file.write(buf, 0, numread);

			} catch (IOException e) {
				return "Couldn't write the file";
			}
		} while (true);
		try {
			file.close();
		} catch (IOException e) {
			return "Couldn't close the file";
		}
		return "Successful";
	}

	private static String getFileName(URL url) {
		String fileName = url.getFile();
		fileName = fileName.replace("%20", " ");
		return fileName.substring(fileName.lastIndexOf('/') + 1);
	}
	
	public static String HTTPrequest(String url) throws Exception{
		HttpClient httpclient = new DefaultHttpClient();
	    HttpResponse response = httpclient.execute(new HttpGet(url));
	    StatusLine statusLine = response.getStatusLine();
	    String responseString = "";
	    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
	        /*
	    	ByteArrayOutputStream out = new ByteArrayOutputStream();
	        response.getEntity().writeTo(out);
	        out.close();
	        responseString = out.toString();
	        //..more logic
	         */
	    	responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
	    } else{
	        //Closes the connection.
	        response.getEntity().getContent().close();
	        throw new IOException(statusLine.getReasonPhrase());
	    }
	    
	    return responseString;
	}

}
